package com.zzw.system.service.Impl;

import com.zzw.model.system.SysUser;
import com.zzw.system.custom.CustomUser;
import com.zzw.system.service.SysMenuService;
import com.zzw.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zzw
 * @date 2023/4/25 11:26
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    /**
     * 根据用户名获取用户对象（获取不到直接抛异常）
     */
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUserName(username);
        if(sysUser==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        if(sysUser.getStatus()==0){
            throw new RuntimeException("用户已停用");
        }

//        获取用户的(按钮)操作权限 ，如增删改查
        List<String> permList = sysMenuService.getUserButtonList(sysUser.getId());

//        转换为spring-security要求的格式数据
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
        for (String perm :permList) {

                authorities.add(new SimpleGrantedAuthority(perm.trim()));

        }

        System.out.println(authorities);
//        原先authorities格式为[1,2]
//        new完后为[{"authority":"1"},{"authority":"2"}]
        return new CustomUser(sysUser, authorities);

    }
}
